package com.it.park.rms.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.it.park.rms.client.model.Action;
import com.it.park.rms.client.model.User;
import com.it.park.rms.client.service.ActionService;
import com.it.park.rms.constant.Global;

public class LoginInterceptor implements HandlerInterceptor{
	Log log=LogFactory.getLog(LoginInterceptor.class);
	
	@Autowired
	private ActionService actionService;
	
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		String uri = request.getRequestURI();
		String actionUrl = uri.substring(uri.indexOf("/",2), uri.length());
		Action action = actionService.selectByUrl(actionUrl);
		if(action != null){
			return true;
		}
		//seesion
		HttpSession session = request.getSession();
		User user = (User) session.getAttribute(Global.USER_SESSION);
		if(user != null){
			return true;
		}
		request.getRequestDispatcher("/admin/login.jsp").forward(request, response);
		return false;
	}

}
